# _*_ coding:utf-8 _*_
# @File  : views.py
# @Time  : 2020-08-31 11:38
# @Author: zizle

""" 用户的其他操作 """
# from datetime import datetime
from fastapi import APIRouter, Query
# from fastapi.encoders import jsonable_encoder
# from utils.verify import oauth2_scheme, decipher_user_token
from status import r_status
# from db.mysql_z import MySqlZ
from db import FAConnection
from .models import UserRole, ModifyUserItem, UserExtensionItem


user_view_router = APIRouter()
#

# @user_view_router.get("/user/phone-exists/", summary="查询手机号是否存在")
# async def get_phone(phone: str = Query(..., min_length = 11, max_length = 11, regex = r'^[1][3-9][0-9]{9}$')):
#     with MySqlZ() as cursor:
#         cursor.execute(
#             "SELECT `id`,`phone` FROM user_user WHERE phone=%s;", phone
#         )
#         is_exists = cursor.fetchone()
#     if is_exists:
#         return {"message": "查询成功!", "is_exists": True}
#     else:
#         return {"message": "查询成功!", "is_exists": False}
#
#
# @user_view_router.put("/user/online/", summary="用户在线时间累计")
# async def update_user_online(
#         machine_uuid: str = Query(..., min_length=36, max_length=42),
#         token: str = Depends(oauth2_scheme)
# ):
#     user_id, user_code = decipher_user_token(token)
#     today_str = datetime.today().strftime("%Y-%m-%d")
#     # 处理uuid(由于2020.11.23修改的客户端重复问题,用户自动登录后客户端为保存machine_uuid只能由此处理)兼容旧版
#     machine_uuid = "{}-{}".format(machine_uuid.rsplit('-', 1)[0], "%04d" % (user_id if user_id else 0))
#     with MySqlZ() as cursor:
#         cursor.execute("SELECT `id`,machine_uuid FROM `basic_client` WHERE machine_uuid=%s;", machine_uuid)
#         client_info = cursor.fetchone()
#         if client_info:  # 客户端存在查询今日是否有记录,有则追加更新,无则新建一条2分钟的记录
#             cursor.execute(
#                 "SELECT `id` online_date FROM basic_client_online WHERE online_date=%s AND client_id=%s;",
#                 (today_str, client_info["id"])
#             )
#             if cursor.fetchone():
#                 cursor.execute(
#                     "UPDATE `basic_client_online` "
#                     "SET total_online=total_online+2 "
#                     "WHERE online_date=%s AND client_id=%s;",
#                     (today_str, client_info["id"])
#                 )
#             else:
#                 cursor.execute(
#                     "INSERT INTO basic_client_online (client_id,online_date,total_online) "
#                     "VALUES (%s,%s,%s);", (client_info["id"], today_str, 2)
#                 )
#         if user_id:  # 用户存在,查询今日是否有记录,有则追加更新,无则新建一条2分钟的记录
#             cursor.execute(
#                 "SELECT id,online_date FROM user_user_online WHERE online_date=%s AND user_id=%s;",
#                 (today_str, user_id)
#             )
#             if cursor.fetchone():
#                 cursor.execute(
#                     "UPDATE `user_user_online` SET total_online=total_online+2 "
#                     "WHERE online_date=%s AND user_id=%s;",
#                     (today_str, user_id)
#                 )
#             else:
#                 cursor.execute(
#                     "INSERT INTO user_user_online (user_id,online_date,total_online) "
#                     "VALUES (%s,%s,%s);", (user_id, today_str, 2)
#                 )
#     return {"message": "用户更新在线时间成功!"}


@user_view_router.get("/all-users/", summary="获取指定的用户")
async def all_users(role: UserRole = Query(...)):
    if role.value not in ['superuser', 'operator', 'collector', 'research', 'normal']:
        return {'code': r_status.VALIDATE_ERROR, 'message': '查询类型错误!', 'data': []}
    sql = 'SELECT id,join_time,recent_login,user_code,username,phone,email,role,avatar,expire,admin_name ' \
          'FROM user_user WHERE role=%s AND is_active=1;'
    db = FAConnection()
    users = db.query(sql, param=[role.value])
    for u in users:
        u['join_time'] = u['join_time'].strftime('%Y-%m-%d %H:%M:%S')
        u['recent_login'] = u['recent_login'].strftime('%Y-%m-%d %H:%M:%S')

    return {'code': r_status.SUCCESS, 'message': '查询用户成功!', 'data': users}


# @user_view_router.get("/user/info/", summary="获取用户的基本信息")  # 个人中心修改密码
# async def get_user_information(user_token: str = Depends(oauth2_scheme)):
#     user_id, user_code = decipher_user_token(user_token)
#     user_code = user_code if user_code else "未知"
#     today = datetime.today().strftime("%Y-%m-%d")
#     # 查询用户的在线时长
#     with MySqlZ() as cursor:
#         cursor.execute("SELECT user_id,SUM(total_online) AS total_online FROM user_user_online "
#                        "WHERE user_id=%s;", (user_id, ))
#         online_obj = cursor.fetchone()
#         cursor.execute("SELECT user_id,total_online FROM user_user_online "
#                        "WHERE user_id=%s AND online_date=%s;", (user_id, today))
#         today_online_obj = cursor.fetchone()
#     if not online_obj:
#         total_online = 0
#     else:
#         total_online = int(online_obj["total_online"])
#     if not today_online_obj:
#         today_online = 0
#     else:
#         today_online = today_online_obj["total_online"]
#     return {"message": "查询成功!",
#             "user": {"user_code": user_code,
#                      "total_online": total_online,
#                      "today_online": today_online}
#             }
#
#
# @user_view_router.put("/user/info/", summary="用户的基本信息修改")
# async def modify_user_information(operator_token: str = Depends(oauth2_scheme), user_info: ModifyUserItem = Body(...)):
#     operate_user, _ = decipher_user_token(operator_token)
#     if not operate_user:
#         raise HTTPException(status_code=401, detail="登录信息过期了,重新登录再操作!")
#     if user_info.modify_id:  # 管理者修改用户信息
#         # 查询管理者身份
#         with MySqlZ() as cursor:
#             cursor.execute("SELECT id,role FROM user_user WHERE id=%s;", (operate_user, ))
#             operator = cursor.fetchone()
#             if not operator or operator["role"] not in ["superuser", "operator"]:
#                 raise HTTPException(status_code=401, detail="非法用户或无权限,无法操作!")
#             if operator["role"] != "superuser" and user_info.role == "operator":
#                 raise HTTPException(status_code=401, detail="您不能设置用户角色为运营者!")
#             # 进行用户信息的修改
#             cursor.execute(
#                 "UPDATE user_user SET username=%(username)s,phone=%(phone)s,email=%(email)s,"
#                 "role=%(role)s,is_active=%(is_active)s,note=%(note)s "
#                 "WHERE id=%(modify_id)s;",
#                 jsonable_encoder(user_info)
#             )
#         return {"message": "修改 {} 的信息成功!".format(user_info.user_code)}
#
#     else:  # 用户自己修改信息
#         return {"message": "修改成功!"}
